package ru.hh.team02.chat.server;

import ru.hh.team02.chat.client.Client;
import ru.hh.team02.chat.client.ClientRegistry;
import ru.hh.team02.chat.logger.SimpleLogger;
import ru.hh.team02.chat.messaging.SendingService;
import ru.hh.team02.chat.utils.ThreadPerTaskExecutor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
    private static final int PORT = 2004;  
    
    private final static String[] roomNames = {"r1", "r2"};

    public static final SimpleLogger adminLogger = 
            new SimpleLogger(System.out);
    
    private static final ThreadPerTaskExecutor executor = 
            new ThreadPerTaskExecutor();
    
    public static final ClientRegistry registry = 
            new ClientRegistry(roomNames);
    public static final SendingService messanger = 
            new SendingService();
    
    ServerSocket listener;
    
    /*
     * listens to a port and spawns handlers
     */
    public void run() {
        try {
            listener = new ServerSocket(PORT);
            System.out.println("waiting for connection...");
            while (true) {
                try  {
                    final Socket connection = listener.accept();
                    executor.execute(new Client(connection));      
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            System.out.println("server went down");
        } finally {
            try {
                listener.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    
}
